package com.jingan.nursinghome.regulatory.dialog.businessside;

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Rect;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;

import com.jingan.nursinghome.regulatory.R;
import com.jingan.nursinghome.regulatory.data.MicrometerTable;
import com.jingan.nursinghome.regulatory.dialog.micrometertable.LoginDialog;
import com.jingan.nursinghome.regulatory.http.KotlinHttp;
import com.jingan.nursinghome.regulatory.model.Qfinfo;
import com.jingan.nursinghome.regulatory.view.TriangelView;

import java.util.ArrayList;
import java.util.List;

import cn.android.support.v7.lib.sin.crown.base.BaseActivity;
import cn.android.support.v7.lib.sin.crown.base.BaseApplication;
import cn.android.support.v7.lib.sin.crown.base.BaseDialog;
import cn.android.support.v7.lib.sin.crown.base.BaseListenner;
import cn.android.support.v7.lib.sin.crown.dialog.RollerLvDialog;
import cn.android.support.v7.lib.sin.crown.kotlin.bean.DateChoose;
import cn.android.support.v7.lib.sin.crown.kotlin.dialog.DateChooseBetweenDialog;
import cn.android.support.v7.lib.sin.crown.kotlin.https.Https;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;
import cn.android.support.v7.lib.sin.crown.utils.StringUtils;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;

/**
 * 企业端
 * Created by 彭治铭 on 2018/3/31.
 */

public class BusinesssideDialog extends BaseDialog {
    private static BusinesssideDialog businesssideDialog;

    public static BusinesssideDialog getInstance(BaseActivity activity) {
        if (isfinish(activity, businesssideDialog)) {
            businesssideDialog = new BusinesssideDialog(activity);
        } else {
            businesssideDialog.show();
        }
        return businesssideDialog;
    }

    public BusinesssideDialog(BaseActivity activity) {
        init(activity, R.layout.dialog_business);
    }

    Button btnNurs,btn_timu;
    SwipeRefreshLayout swipeRefreshLayout;
    RecyclerView recyclerView;
    TextView txt_title;//標題
    TextView txt_title2;//区级端
    Button date_order;//日期顺序
    Button date_reverse;//日期倒叙

    DateChoose dateChooseStart = new DateChoose();//开始日期
    DateChoose dateChooseEnd = new DateChoose();//结束日期
    DateChooseBetweenDialog dateChooseBetweenDialog;//日期选择框

    @Override
    protected void initUI() {
        btnNurs = (Button) findViewById(R.id.btn_nursi);
        btn_timu= (Button) findViewById(R.id.btn_timu);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.mySwipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeColors(Color.parseColor("#FF8080"), Color.parseColor("#FFFF00"), Color.parseColor("#00FF40"), Color.parseColor("#00FFFF"), Color.parseColor("#0080C0"));
        recyclerView = (RecyclerView) findViewById(R.id.myRecyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        txt_title = (TextView) findViewById(R.id.txt_title);
        txt_title2 = (TextView) findViewById(R.id.txt_title2);
        date_order = (Button) findViewById(R.id.date_order);
        date_reverse = (Button) findViewById(R.id.date_reverse);

        dateChooseBetweenDialog = new DateChooseBetweenDialog(activity, dateChooseStart, dateChooseEnd,true,true);//日期选择框
        dateChooseBetweenDialog.dismiss();
        //日期选择
        dateChooseBetweenDialog.setCallBack(new Function2<DateChoose, DateChoose, Unit>() {
            @Override
            public Unit invoke(DateChoose dateChoose, DateChoose dateChoose2) {
                Log.e("test", "回调:\t" + dateChoose.toString().compareTo(dateChoose2.toString()));
                if (dateChoose.toString().compareTo(dateChoose2.toString()) > 0) {
                    baseActivity.SnackbarMake("开始日期不能大于结束日期", true, getParentView());
                }else {
                    starttime=dateChoose.toString();
                    endtime=dateChoose2.toString();
                    date_order.setText(starttime);//开始时间
                    date_reverse.setText(endtime);//结束时间
                    initData();
                }
                return null;
            }
        });
    }

    private long exitTime = 0;
    int current = 3;
    int allPotons = 4;//查询全部的下标
    int current2 = 0;
    int allPotons2 = 0;//查询全部题目的下标
    String jlyID;//当前选中敬老院id
    String starttime;//开始时间
    String endtime;//结束时间
    String stname;//套题名称

    //fixme ==============================================================================================================================================初始化数据
    private void initData() {
//        Http.getInstance().qfinfo(getActivity(), jlyID, new BaseListenner<List<Qfinfo>>() {
//            @Override
//            public void onResult(List<Qfinfo> result) {
//                //Log.e("test","巡檢數據個數:\t"+result.size());
//                swipeRefreshLayout.setRefreshing(false);
//                models.clear();
//                models.addAll(result);
//                recyclerView.getAdapter().notifyDataSetChanged();
//            }
//        });
        KotlinHttp.INSTANCE.qfinfo(jlyID, starttime, endtime, stname, baseActivity, new BaseListenner<ArrayList<Qfinfo>>() {

            @Override
            public void onResult(ArrayList<Qfinfo> result) {
                swipeRefreshLayout.setRefreshing(false);
                models.clear();
                models.addAll(result);
                recyclerView.getAdapter().notifyDataSetChanged();
            }
        });

    }

    boolean b = true;

    @Override
    protected void listener() {
        recyclerView.setAdapter(new MyAdapter());
        recyclerView.getAdapter().notifyDataSetChanged();
        //下拉刷新事件监听
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                if (jlyID == null) {
//                    return;
//                }
                swipeRefreshLayout.setRefreshing(true);
                starttime=null;
                endtime=null;
                date_order.setText("开始时间");
                date_reverse.setText("结束时间");
                initData();
            }
        });
        //退出登录
        findViewById(R.id.txt_login_out).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginOrOut(false);
                dismiss();
            }
        });
        date_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (!b && models.size() > 0) {
//                    date_order.setBackgroundColor(Color.parseColor("#66CCFF"));
//                    date_reverse.setBackgroundColor(Color.parseColor("#A1A1A1"));
//                    //日期順序
////                    Collections.reverse(models);
////                    recyclerView.getAdapter().notifyDataSetChanged();
//                    b = true;
//                    //开始时间
//                    dateChooseBetweenDialog.star().show();
//                }
                //开始时间
                dateChooseBetweenDialog.star().show();
            }
        });
        date_reverse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (b && models.size() > 0) {
//                    date_reverse.setBackgroundColor(Color.parseColor("#66CCFF"));
//                    date_order.setBackgroundColor(Color.parseColor("#A1A1A1"));
//                    //日期倒序
////                    Collections.reverse(models);
////                    recyclerView.getAdapter().notifyDataSetChanged();
//                    //结束时间
//                    dateChooseBetweenDialog.end().show();
//                    b = false;
//                }
                dateChooseBetweenDialog.end().show();
            }
        });
        if (MicrometerTable.getInstance().getUser().getUtype().equals("3")) {
            //企业端（可以选择多个敬老院）
            txt_title.setVisibility(View.INVISIBLE);
            txt_title2.setVisibility(View.VISIBLE);
            //敬老院集合
            final List<String> items = new ArrayList<String>();
            for (int i = 0; i < MicrometerTable.getInstance().getJlys().size(); i++) {
                if(MicrometerTable.getInstance().getJlys()!=null&&MicrometerTable.getInstance().getJlys().get(i)!=null){
                    items.add(MicrometerTable.getInstance().getJlys().get(i).getName());
                }
            }
            if (items.size() > 0) {
                if (items.size() < allPotons) {
                    allPotons = items.size() - 1;
                }
                items.add(allPotons, "全部");
                current = allPotons;
            }
            Log.e("test", "敬老院数量:\t" + items.size());
            btnNurs.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (items.size() <= 0) {
                        for (int i = 0; i < MicrometerTable.getInstance().getJlys().size(); i++) {
                            items.add(MicrometerTable.getInstance().getJlys().get(i).getName());
                        }
                        if (items.size() < allPotons) {
                            allPotons = items.size() - 1;
                        }
                        items.add(allPotons, "全部");
                        current = allPotons;
                    }
                    //底部巡机构选择
                    RollerLvDialog.getInstance(getActivity()).setItems(items, 7).setCircle(false).setBtnInfoText("请选择巡检敬老院").selectIem(current).setPositiveListener(new RollerLvDialog.PositiveListener() {
                        @Override
                        public void onItemSelect(String item, int position) {
                            btnNurs.setText(item);
                            if (position == allPotons) {
                                //查询全部
                                jlyID=null;
                            } else {
                                current = position;
                                jlyID = MicrometerTable.getInstance().getJlyID(item);
                            }
                            initData();
                        }
                    }).show();
                }
            });
            //企业端多了一个选择按钮，所以最后一个item的间距得做调整。
            recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {

                @Override
                public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
                    super.getItemOffsets(outRect, itemPosition, parent);
                    if (itemPosition == (recyclerView.getAdapter().getItemCount() - 1)) {
                        outRect.bottom = ProportionUtils.getInstance().adapterInt(260);
                    }else {
                        outRect.bottom =0;
                    }
                }
            });

        } else {

            //企业端多了一个选择按钮，所以最后一个item的间距得做调整。
            recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {

                @Override
                public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
                    super.getItemOffsets(outRect, itemPosition, parent);
                    if (itemPosition == (recyclerView.getAdapter().getItemCount() - 1)) {
                        outRect.bottom = ProportionUtils.getInstance().adapterInt(130);
                    }else {
                        outRect.bottom =0;
                    }
                }
            });

            txt_title.setVisibility(View.VISIBLE);
            txt_title2.setVisibility(View.INVISIBLE);
            txt_title.setText("养老机构端");
            //只有一个默认静老院
            jlyID = MicrometerTable.getInstance().getUser().getOid().trim();
            String name = MicrometerTable.getInstance().getJlyName(jlyID);
            //txt_title.setText("普陀A养老机构");
            txt_title.setText(name);
            btnNurs.setVisibility(View.GONE);
            initData();
        }

        //题目集合
        final List<String> items2 = new ArrayList<String>();
        for (int i = 0; i < MicrometerTable.getInstance().getNames().size(); i++) {
            if(MicrometerTable.getInstance().getNames()!=null&&MicrometerTable.getInstance().getNames().get(i)!=null){
                items2.add(MicrometerTable.getInstance().getNames().get(i));
            }
        }
        if (items2.size() > 0) {
            if (items2.size() < allPotons) {
                allPotons2 = items2.size() - 1;
            }
            items2.add(allPotons2, "全部");
            current2 = allPotons2;
        }
        btn_timu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (items2.size() <= 0) {
                    for (int i = 0; i < MicrometerTable.getInstance().getNames().size(); i++) {
                        items2.add(MicrometerTable.getInstance().getNames().get(i));
                    }
                    if (items2.size() < allPotons2) {
                        allPotons2 = items2.size() - 1;
                    }
                    items2.add(allPotons2, "全部");
                    current2 = allPotons2;
                }
                //底部巡机构选择
                RollerLvDialog.getInstance(getActivity()).setItems(items2, 8).setCircle(false).setBtnInfoText("请选择题目类型").selectIem(current2).setPositiveListener(new RollerLvDialog.PositiveListener() {
                    @Override
                    public void onItemSelect(String item, int position) {
                        btn_timu.setText(item);
                        if (position == allPotons2) {
                            //查询全部
                            stname=null;
                        } else {
                            current2 = position;
                            stname = item;
                        }
                        initData();
                    }
                }).show();
            }
        });


        //按键屏蔽
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if ((System.currentTimeMillis() - exitTime) > 2000) {
                        baseActivity.SnackbarMake("再按一次退出", true, getParentView());
                        exitTime = System.currentTimeMillis();
                    } else {
                        BaseApplication.getInstance().exit();
                    }
                    System.gc();
                    return true;
                }
                return false;
            }
        });

        //初始化数据
        initData();
    }

    //true登录，false退出登录
    private void loginOrOut(boolean login) {
        LoginDialog.getInstance(getBaseActivity(), login, new BaseListenner() {
            @Override
            public void onResult(Object result) {
                //登录成功回调

            }
        });
    }

    @Override
    protected void recycleView() {

    }

    @Override
    protected boolean isLocked() {
        return true;
    }

    @Override
    protected boolean isDismiss() {
        return false;
    }

    private List<Qfinfo> models = new ArrayList();

    class MyAdapter extends RecyclerView.Adapter {

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView txt_date;//日期
            TextView txt_time;//时间
            TextView txt_people;//巡检人
            TextView txt_totalscrol;//总分
            TextView getScore;//得分
            TextView txt_prop;//得分率
            TriangelView taringe;//標號
            TextView txt_delay;//詳情

            public MyViewHolder(View itemView) {
                super(itemView);
                txt_date = itemView.findViewById(R.id.txt_date);
                txt_time = itemView.findViewById(R.id.txt_time);
                txt_totalscrol = itemView.findViewById(R.id.txt_totalscrol);
                getScore = itemView.findViewById(R.id.getScore);
                txt_people = itemView.findViewById(R.id.txt_people);
                txt_prop = itemView.findViewById(R.id.txt_prop);
                taringe = itemView.findViewById(R.id.taringe);
                txt_delay = itemView.findViewById(R.id.txt_delay);
            }
        }

        class EmptyViewHolder extends RecyclerView.ViewHolder {
            public EmptyViewHolder(View itemView) {
                super(itemView);
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            if (viewType == viewTypeEmpty) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.empty_view, parent, false);
                return new EmptyViewHolder(view);
            } else {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_business, parent, false);
                return new MyViewHolder(view);
            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof MyViewHolder) {
                MyViewHolder myViewHolder = (MyViewHolder) holder;
                if (position % 2 == 0) {
                    Animation animation_alpha = AnimationUtils.loadAnimation(getActivity(), R.anim.zebra_right_in_without_alpha);
                    holder.itemView.startAnimation(animation_alpha);
                } else {
                    Animation animation_alpha = AnimationUtils.loadAnimation(getActivity(), R.anim.zebra_left_in_without_alpha);
                    holder.itemView.startAnimation(animation_alpha);
                }
                final Qfinfo qfinfo = models.get(position);
                myViewHolder.txt_date.setText(qfinfo.getDate());//日期
                myViewHolder.txt_time.setText(qfinfo.getTime());//时间
                myViewHolder.txt_people.setText(qfinfo.getAccount());//巡检人

                myViewHolder.txt_totalscrol.setText(qfinfo.getTotal() + "分");//总分
                myViewHolder.getScore.setText(qfinfo.getTotal_hair() + "分");//得分
                myViewHolder.txt_prop.setText(qfinfo.getScoring_rate() + "%");//得分率
                myViewHolder.taringe.setIndex(position + 1 + "");//標號
                myViewHolder.txt_delay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //詳情
                        qfinfo.setJly(MicrometerTable.getInstance().getJlyName(jlyID));//巡检机构名称
                        MicrometerTable.getInstance().setQfinfo(qfinfo);
                        MicrometerTableDetailsDialog.getInstance(getBaseActivity(), qfinfo.getId());
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return models.size() > 0 ? models.size() : 1;
        }

        int viewTypeEmpty = -1;

        @Override
        public int getItemViewType(int position) {
            if (models.size() <= 0) {
                return viewTypeEmpty;
            }
            return position;
        }
    }

}
